package com.demo28_找出字符串中第一个匹配项的下标;

public class Solution {
    public int strStr(String haystack, String needle) {
        int result = -1 ;
        for (int i = 0; i < haystack.length(); i++) {

            for (int j = 0; j < needle.length(); j++) {
                if (i+j==haystack.length()){
                    return result;
                }
                if (needle.charAt(j)!=haystack.charAt(i+j)){
                    break;
                }
                if (j==needle.length()-1){
                    return i;
                }
            }

        }
        return result;
    }

    // 代码优化
    public static int strStr2(String haystack, String needle) {
        int result = -1 ;
        // 2个数组长度的差值+1 即为短数组可以挪动比较的最大次数
        for (int i = 0; i < haystack.length()-needle.length()+1; i++) {
            if (haystack.substring(i,i+needle.length()).equals(needle)){
                return i;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int i = solution.strStr2("abcd", "cd");
        System.out.println(i);
    }

}
